package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"net/http"
	"time"
	"websocket_exam/api/request"
	"websocket_exam/consts"
	"websocket_exam/internal/dao"
	"websocket_exam/internal/model"
	"websocket_exam/internal/queue"
	"websocket_exam/pkg"
)

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"mes":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile}, &user)
	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"mes":  "账号已存在，请前去登录",
			"data": false,
		})
		return
	}
	result := dao.Create(&model.User{
		Username: req.Username,
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
		TypeUser: req.TypeUser,
		Status:   req.Status,
		Image:    req.Image,
	})
	if !result {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"mes":  "注册失败",
			"data": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"mes":  "注册成功",
		"data": true,
	})

}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"mes":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile, Password: pkg.Md5(req.Password)}, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"mes":  "账号或者密码错误",
			"data": false,
		})
		return
	}
	token, err := gojwt.NewJWT(consts.Jwt_KEY).CreateToken(gojwt.CustomClaims{
		ID:          user.Id,
		AuthorityId: user.TypeUser,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() * 3600 * 24 * 7,
		},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"mes":  "token生成失败",
			"data": false,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"mes":  "ok",
		"data": token,
	})

}

func GetUser(c *gin.Context) {
	var req request.GetUser
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"mes":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	dto := dao.PageDto{
		Page:     req.Page,
		PageSize: req.PageSize,
	}
	var user []model.User
	paginate, _ := dao.Paginate(&model.User{}, dto, &user)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"mes":  "用户列表展示成功",
		"data": paginate,
	})

}

func SendMessage(c *gin.Context) {
	var req request.SendMessage
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"mes":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	notice := model.Notice{
		Title:   req.Title,
		Content: req.Content,
	}

	go queue.PublishPub(consts.SEND_GROUP, req.Content)
	dao.Create(&notice)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"mes":  "公告发布成功",
		"data": true,
	})

}
